import express from 'express';
import { getPool } from '../database/db.js';
import { log } from '../utils/logger.js';

const router = express.Router();

/**
 * 调试接口 - 检查数据库类型和用户列表
 */
router.get('/db-info', async (req, res) => {
  try {
    const pool = getPool();
    
    // 获取数据库信息
    const dbInfo = {
      type: 'MySQL',
      host: process.env.DB_HOST,
      port: process.env.DB_PORT,
      database: process.env.DB_NAME,
      user: process.env.DB_USER,
      charset: process.env.DB_CHARSET,
      timezone: process.env.DB_TIMEZONE
    };
    
    // 获取所有用户
    const [users] = await pool.execute(
      'SELECT id, username, email, totp_enabled, created_at FROM users'
    );
    
    // 获取所有表
    const [tables] = await pool.execute('SHOW TABLES');
    
    // 获取数据库版本
    const [version] = await pool.execute('SELECT VERSION() as version');
    
    log.system('调试信息查询', { userCount: users.length });
    
    res.json({
      success: true,
      data: {
        database: {
          type: dbInfo.type,
          host: dbInfo.host,
          port: dbInfo.port,
          name: dbInfo.database,
          user: dbInfo.user,
          charset: dbInfo.charset,
          timezone: dbInfo.timezone,
          version: version[0]?.version
        },
        tables: tables.map(t => Object.values(t)[0]),
        users: users,
        userCount: users.length,
        timestamp: new Date().toISOString()
      }
    });
  } catch (error) {
    log.error('获取调试信息失败', { error: error.message });
    res.status(500).json({
      success: false,
      message: '获取调试信息失败',
      error: error.message,
      stack: error.stack
    });
  }
});

/**
 * 创建测试用户
 */
router.post('/create-test-user', async (req, res) => {
  try {
    const pool = getPool();
    const bcrypt = await import('bcryptjs');
    
    const username = 'samygood';
    const password = 'samyxue8341';
    const email = 'admin@laoxue.com';
    
    // 加密密码
    const hashedPassword = await bcrypt.default.hash(password, 10);
    
    // 检查用户是否存在
    const [existing] = await pool.execute(
      'SELECT id FROM users WHERE username = ?',
      [username]
    );
    
    if (existing.length > 0) {
      // 更新密码
      await pool.execute(
        'UPDATE users SET password = ?, email = ?, totp_enabled = 0, totp_secret = NULL WHERE username = ?',
        [hashedPassword, email, username]
      );
      
      log.system('测试用户密码已更新', { username });
      
      return res.json({
        success: true,
        message: '用户已存在，密码已更新',
        data: {
          username,
          password,
          email,
          action: 'updated'
        }
      });
    }
    
    // 创建新用户
    const [result] = await pool.execute(
      'INSERT INTO users (username, password, email, totp_enabled) VALUES (?, ?, ?, ?)',
      [username, hashedPassword, email, 0]
    );
    
    log.system('测试用户创建成功', { username, userId: result.insertId });
    
    res.json({
      success: true,
      message: '测试用户创建成功',
      data: {
        userId: result.insertId,
        username,
        password,
        email,
        action: 'created'
      }
    });
  } catch (error) {
    log.error('创建测试用户失败', { error: error.message });
    res.status(500).json({
      success: false,
      message: '创建测试用户失败',
      error: error.message
    });
  }
});

/**
 * 测试数据库连接
 */
router.get('/test-connection', async (req, res) => {
  try {
    const pool = getPool();
    const connection = await pool.getConnection();
    
    // 测试查询
    const [result] = await connection.execute('SELECT 1 + 1 AS result');
    
    connection.release();
    
    res.json({
      success: true,
      message: 'MySQL连接正常',
      data: {
        type: 'MySQL',
        host: process.env.DB_HOST,
        database: process.env.DB_NAME,
        testQuery: result[0],
        timestamp: new Date().toISOString()
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: 'MySQL连接失败',
      error: error.message,
      details: {
        host: process.env.DB_HOST,
        database: process.env.DB_NAME
      }
    });
  }
});

export default router;

